<template>
  <el-dialog
    title='新增环保设施基本信息'
    :visible.sync='state'
    :modal-append-to-body='false'
    :close-on-click-modal='false'
    :close-on-press-escape='false'
    @close='closeBox'>

    <el-form :model='form' :rules='rules' ref='form' size='small'>

      <el-row type='flex' class='row-bg' justify='space-between' align='middle'>
        <el-col :span='12' class='grid-content'>
          <el-form-item label='选择企业：' :label-width='formLabelWidth' prop='companyId'>

            <el-select size='medium' v-model="form.companyId" placeholder="请选择">
              <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id">{{item.name}}</el-option>
            </el-select>

          </el-form-item>
        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between'>
        <el-col :span='12' class='grid-content'>

          <el-form-item label='环保设施名称：' :label-width='formLabelWidth' prop='name'>
            <el-input size='small' v-model='form.name' autocomplete='off'></el-input>
          </el-form-item>

        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between'>
        <el-col :span='12' class='grid-content'>

          <el-form-item label='委托合同：' :label-width='formLabelWidth' prop='contract'>
            <el-upload class='oss-upload' ref='upload' action=''
              :multiple='true'
              :file-list="form.contract"
              :on-remove='handleRemoveContractAttr'
              :on-change='handleChangeContractAttr'
              :auto-upload='false'>
              <el-button slot='trigger' size='small' type='primary'>选取文件</el-button>
              <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-form-item>

        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between'>
        <el-col :span='12' class='grid-content'>

          <el-form-item label='设计方案 ：' :label-width='formLabelWidth' prop='designScheme'>
            <el-upload class='oss-upload' ref='upload' action=''
              :multiple='true'
              :file-list="form.designScheme"
              :on-remove='handleRemoveAttr2'
              :on-change='handleChangeAttr2'
              :auto-upload='false'>
              <el-button slot='trigger' size='small' type='primary'>选取文件</el-button>
              <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-form-item>

        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between'>
        <el-col :span='12' class='grid-content'>

          <el-form-item label='施工监理资料：' :label-width='formLabelWidth' prop='constructionSupervision'>
            <el-upload class='oss-upload' ref='upload' action=''
              :multiple='true'
              :file-list="form.constructionSupervision"
              :on-remove='handleRemoveAttr3'
              :on-change='handleChangeAttr3'
              :auto-upload='false'>
              <el-button slot='trigger' size='small' type='primary'>选取文件</el-button>
              <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-form-item>

        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between'>
        <el-col :span='12' class='grid-content'>

          <el-form-item label='验收资料：' :label-width='formLabelWidth' prop='acceptanceData'>
            <el-upload class='oss-upload' ref='upload' action=''
              :multiple='true'
              :file-list="form.acceptanceData"
              :on-remove='handleRemoveAttr4'
              :on-change='handleChangeAttr4'
              :auto-upload='false'>
              <el-button slot='trigger' size='small' type='primary'>选取文件</el-button>
              <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-form-item>

        </el-col>
      </el-row>

      <el-divider></el-divider>
      <el-row justify='end' align='middle'>
        <el-col :span='24'>
          <el-form-item style='float: right'>
            <el-button @click="cancel('form')">取 消</el-button>
            <el-button type='primary' @click="submit('form')">确 定</el-button>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- <el-form-item>
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button type='primary' @click="submit('form')">确 定</el-button>
      </el-form-item> -->
    </el-form>
  </el-dialog>
</template>
<script>


export default {
  components: {

  },
  props: ['editItem'],
  computed: {},
  data() {
    return {
      formLabelWidth: '120px',
      state: true,

      sigData: null,
      companyList: [],

      form: {
        companyId: '',
        name: '',
        type: "VOCS",
        
        contract: [],
        designScheme: [],
        constructionSupervision: [],
        acceptanceData: [],
    
      },
      rules: {
        companyId: [{ required: true, message: '请选择企业', trigger: 'change' }],
        name: [{ required: true, message: '请输入环保设施名称', trigger: 'blur' }],

        // contract: [{ type: 'array', required: true, message: '请上传合同资料', trigger: 'blur' }],

      },
    };
  },
  created() {
    this.companyLists();
    this.form = Object.assign({}, this.form, this.editItem);
    this.getSig();
  },
  mounted() {},
  methods: {
    closeBox() {
      this.state = false;
      this.$ge.$emit('biz-waste-env-pro-change-search');
    },
    cancel(formName) {
      this.state = false;
      this.$refs[formName].resetFields();
    },
    //查询企业列表
    companyLists() {
      this.$get('/biz-company/list', {})
        .then((result) => {
          if (result.code == 200 && result.data) {
            this.companyList = result.data;
          }
        })
        .catch((error) => {
          this.companyList = [];
        });
    },
    handleRemoveContractAttr(file, fileList) {
      this.form.contract = fileList;
    },
    handleChangeContractAttr(file, fileList) {
      //类型（jpg, png）和大小(2M 以内)
      // const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt2M = file.raw.size / 1024 / 1024 < 500;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 jpg 或者 png 格式!');
      //     return;
      // }
      if (!isLt2M) {
        this.$message.error('单个文件大小不能超过 500MB!');
        return;
      }
      // if(isJPG && isLt2M) {
      //   this.fileList.push(file);
      // }
      this.form.contract = fileList;
      return false;
    },
    handleRemoveAttr2(file, fileList) {
      this.form.designScheme = fileList;
    },
    handleChangeAttr2(file, fileList) {
      //类型（jpg, png）和大小(2M 以内)
      // const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt2M = file.raw.size / 1024 / 1024 < 500;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 jpg 或者 png 格式!');
      //     return;
      // }
      if (!isLt2M) {
        this.$message.error('单个文件大小不能超过 500MB!');
        return;
      }
      // if(isJPG && isLt2M) {
      //   this.fileList.push(file);
      // }
      this.form.designScheme = fileList;
      return false;
    },
    handleRemoveAttr3(file, fileList) {
      this.form.constructionSupervision = fileList;
    },
    handleChangeAttr3(file, fileList) {
      //类型（jpg, png）和大小(2M 以内)
      // const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt2M = file.raw.size / 1024 / 1024 < 500;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 jpg 或者 png 格式!');
      //     return;
      // }
      if (!isLt2M) {
        this.$message.error('单个文件大小不能超过 500MB!');
        return;
      }
      // if(isJPG && isLt2M) {
      //   this.fileList.push(file);
      // }
      this.form.constructionSupervision = fileList;
      return false;
    },
    handleRemoveAttr4(file, fileList) {
      this.form.acceptanceData = fileList;
    },
    handleChangeAttr4(file, fileList) {
      //类型（jpg, png）和大小(2M 以内)
      // const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt2M = file.raw.size / 1024 / 1024 < 500;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 jpg 或者 png 格式!');
      //     return;
      // }
      if (!isLt2M) {
        this.$message.error('单个文件大小不能超过 500MB!');
        return;
      }
      // if(isJPG && isLt2M) {
      //   this.fileList.push(file);
      // }
      this.form.acceptanceData = fileList;
      return false;
    },
    getSig() {
      this.$get('/oss/getUploadOssSignature')
        .then((result) => {
          if (result.code == 200 && result.data) {
            this.sigData = result.data;
          }
        })
        .catch((error) => {
          this.sigData = null;
        });
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$WLoading();

          this.form.contract = this.submitUpload(this.form.contract);
          this.form.designScheme = this.submitUpload(this.form.designScheme);
          this.form.constructionSupervision = this.submitUpload(this.form.constructionSupervision);
          this.form.acceptanceData = this.submitUpload(this.form.acceptanceData);
          var param = {};
          param = Object.assign({}, this.form, param);
       
          this.$postJson('/biz-ep-facilities/update', param)
            .then((result) => {
              if (result.code == 200) {
                this.$message.success(result.msg);

                //关闭弹框并刷新列表
                this.closeBox(formName);
              } else this.$message.error(result.msg);
              this.$cancelLoading();
            })
            .catch((error) => {
              //添加用户异常
              this.$message.error('添加失败');
              this.$cancelLoading();
            });
        } else {
          console.log('用户填写有误！');
          return false;
        }
      });
    },
    submitUpload(allAttr) {
      
      let sigData = this.sigData;//提前请求拿到的签名信息

      let nowAllAttr = [];
      if(!allAttr || allAttr.length == 0) 
        return nowAllAttr;

      allAttr.forEach(element => {
        let ossData = new FormData()//创建oss数据对象
        ossData.append('name', element.name)
        let keyValue = 'ep/web/' + this.uuid() + '::' + element.name
        ossData.append('key', keyValue)
        ossData.append('policy', sigData.policy)
        ossData.append('OSSAccessKeyId', sigData.accessId)
        ossData.append('success_action_status', 200)
        ossData.append('Signature', sigData.signature)
        ossData.append('file', element.raw)

        this.$postFormData(sigData.ossDomain, ossData)
          .then((result) => {})
          .catch((error) => {});

        nowAllAttr.push({
          name: element.name,
          url: sigData.ossDomain +'/'+ keyValue,
          size: element.size,
        })
      });

      return nowAllAttr;
    },

  },
};
</script>

<style>
.el-select {
  width: 100%;
}

.vue-treeselect__input {
  border: 0 !important;
}

.el-form-item__content {
  text-align: left;
}

/* 上传样式 start */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/* 上传样式 end */
</style>
